package com.hebtu.helper.modules.sys.service.impl;


import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hebtu.helper.modules.sys.dao.SysUserRoleDao;
import com.hebtu.helper.modules.sys.service.SysUserRoleService;
import com.hebtu.helper.modules.sys.entity.SysUserRoleEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

    /**
     * 根据用户ID查询他的所有角色id
     * @param userId  用户id
     * @return
     */
    @Override
    public List<Long> queryRolesByUserID(Long userId) {
        return baseMapper.queryRolesByUserId(userId);
    }

    @Override
    public Integer saveAll(Long userId, List<Long> roleIds) {
        Integer number=0;
        for (Long roleId : roleIds) {
            SysUserRoleEntity sysUserRoleEntity=new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);
            number+=baseMapper.insert(sysUserRoleEntity);
        }
        return number;
    }

    /**
     * 修改
     * 1.先删除原来的角色信息
     * 2.增加新的信息
     * @param userId
     * @param roleIds
     */
    @Override
    @Transactional
    public void update(Long userId, List<Long> roleIds) {
        delete(userId);
        saveAll(userId, roleIds);
    }

    /**
     * 根据userid删除对应角色
     * @param userId
     * @return
     */
    @Override
    public Integer delete(Long userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        return baseMapper.deleteByMap(map);
    }
}
